<!-- 维修待派工列表 -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    <template #buts>
      <a-button type="primary" @click="repairFault">
        <template #icon>
          <icon-plus></icon-plus>
        </template>
        <template #default>故障报修</template>
      </a-button>
      <!-- <a-button
        type="primary"
        :style="{
          backgroundColor: '#31C27C',
          color: '#fff',
        }"
        @click="newRepair"
      >
        <template #icon>
          <icon-subscribe-add></icon-subscribe-add>
        </template>
        <template #default>新建维修任务</template>
      </a-button> -->
    </template>
  </pageHeader>
  <div class="content">
    <div class="content-header">
      <div>
        <a-input-group>
          <a-select
            :style="{
              flex: 1,
            }"
            v-model="currSelectName"
            placeholder="请选择"
            @change="search"
          >
            <a-option value="number">维修单号</a-option>
            <a-option value="equipNumber">设备编码</a-option>
          </a-select>
          <a-input-search
            search-button
            :style="{
              flex: 3,
              backgroundColor: '#fff',
              border: '1px solid #ccc',
            }"
            placeholder="请输入"
            v-model="currNumber"
            @search="search"
          >
          </a-input-search>
        </a-input-group>
      </div>
      <div
        :style="{
          marginLeft: '20px',
        }"
      >
        <!-- <span> 设备名称： </span> -->
        <a-input-search
          :style="{ width: 'auto' }"
          placeholder="请输入设备名称"
          v-model="currEquipName"
          search-button
          @search="search"
        >
          <template #prefix>设备名称：</template>
          <template #button-icon>
            <icon-search />
          </template>
        </a-input-search>
      </div>
      <a-button
        type="primary"
        :style="{
          marginLeft: '10px',
        }"
        @change="search"
      >
        <template #icon>
          <icon-search />
        </template>
        <template #default>搜索</template>
      </a-button>
      <a-button
        type="outline"
        :style="{
          marginLeft: '10px',
          borderColor: '#ccc',
          color: '#ccc',
        }"
        @click="reset"
      >
        <template #icon>
          <icon-refresh />
        </template>
        <template #default>重置</template>
      </a-button>
      <a-button
        :style="{
          marginLeft: '10px',
        }"
        type="primary"
        @click="open"
      >
        维修派工
      </a-button>
    </div>

    <div
      :style="{
        marginTop: '20px',
      }"
    >
      <TableTurn :args="args" :table-data="getData" ref="tableRef">
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>

        <a-table-column
          :width="150"
          align="center"
          title="维修单号"
          data-index="number"
        >
        </a-table-column>

        <a-table-column
          :width="150"
          align="center"
          title="设备名称"
          data-index="equipName"
        >
        </a-table-column>
        <a-table-column
          :width="150"
          align="center"
          title="设备编码"
          data-index="equipNumber"
        >
        </a-table-column>
        <!-- <a-table-column :width="150" align="center" title="故障描述">
          <template #cell="{ record }">
            <a-button type="text" @click="goDetail(record, 2)">查看</a-button>
          </template>
        </a-table-column> -->

        <a-table-column
          :width="150"
          align="center"
          title="报修人"
          data-index="reporterName"
        >
        </a-table-column>
        <a-table-column :width="200" align="center" title="报修时间">
          <template #cell="{ record }">
            {{ `${dayjs(record.reporterTime).format('YYYY-MM-DD HH:mm:ss')}` }}
          </template>
        </a-table-column>

        <a-table-column
          :width="150"
          align="center"
          title="维修人"
          data-index="repairerName"
        >
        </a-table-column>
        <a-table-column :width="200" align="center" title="维修开始时间">
          <template #cell="{ record }">
            {{
              record.repairBeginTime === 0
                ? '-'
                : `${dayjs(record.repairBeginTime).format(
                    'YYYY-MM-DD HH:mm:ss'
                  )}`
            }}
          </template>
        </a-table-column>

        <a-table-column :width="200" align="center" title="维修结束时间">
          <template #cell="{ record }">
            {{
              record.repairEndTime === 0
                ? '-'
                : `${dayjs(record.repairEndTime).format('YYYY-MM-DD HH:mm:ss')}`
            }}
          </template>
        </a-table-column>
        <!-- <a-table-column :width="150" align="center" title="故障分析及处理">
          <template #cell="{ record }">
            <a-button type="text" @click="goDetail(record, 4)">查看</a-button>
          </template>
        </a-table-column> -->
        <a-table-column
          :width="150"
          align="center"
          title="维修状态"
          fixed="right"
        >
          <template #cell="{ record }">
            <div class="repair-state">
              <div
                class="cycle"
                :class="
                  record.repairState === 1
                    ? 'waitJob-cycle'
                    : record.repairState === 2
                    ? 'waitRepair-cycle'
                    : record.repairState === 3
                    ? 'running-cycle'
                    : record.repairState === 4
                    ? 'needOut-cycle'
                    : record.repairState === 5
                    ? 'outing-cycle'
                    : 'finish-cycle'
                "
              >
              </div>
              <div
                :class="
                  record.repairState === 1
                    ? 'waitJob'
                    : record.repairState === 2
                    ? 'waitRepair'
                    : record.repairState === 3
                    ? 'running'
                    : record.repairState === 4
                    ? 'needOut'
                    : record.repairState === 5
                    ? 'outing'
                    : 'finish'
                "
                >{{
                  record.repairState === 1
                    ? '待派工'
                    : record.repairState === 2
                    ? '待维修'
                    : record.repairState === 3
                    ? '进行中'
                    : record.repairState === 4
                    ? '需委外'
                    : record.repairState === 5
                    ? '已委外'
                    : '已完工'
                }}</div
              >
            </div>
          </template>
        </a-table-column>

        <!-- 操作item -->
        <a-table-column align="center" :width="300" fixed="right" title="操作">
          <template #cell="{ record }">
            <!-- <a-button
              type="text"
              :style="{
                backgroundColor: '#31C27C',
                color: '#fff'
              }"
              v-if="
                record.repairState === 1 ||
                record.repairState === 2 ||
                record.repairState === 3 ||
                record.repairState === 4
              "
              @click="
                goDetail(
                  record,
                  record.repairState === 1
                    ? 3
                    : record.repairState === 2
                    ? 4
                    : record.repairState === 3
                    ? 4
                    : -1
                )
              "
            >
              {{
                record.repairState === 1
                  ? '派工'
                  : record.repairState === 2
                  ? '维修'
                  : record.repairState === 3
                  ? '编辑'
                  : record.repairState === 4
                  ? '委外'
                  : ''
              }}
            </a-button> -->

            <a-button type="text" @click="goDetail(record, 5)"
              >维修详情</a-button
            >
            <a-popconfirm
              @ok="deleteItem(record.id)"
              content="确定删除吗"
              type="error"
            >
              <a-button
                type="text"
                :style="{
                  color: 'red',
                }"
                >删除</a-button
              >
            </a-popconfirm>
          </template>
        </a-table-column>
      </TableTurn>
      <equipmentRepair
        :type="type"
        :form="form.list"
        v-model:visible="repairVisible"
        @equipmentEmit="equipmentEmit"
      ></equipmentRepair>
    </div>
  </div>
  <personnelModel
    :title="'请选择执行维修人员'"
    @personnelId="changePersonnelId"
    v-model:personnelVisible="personnelVisible"
  />
</template>

<script lang="ts" setup>
  import { Message } from '@arco-design/web-vue';
  import { useUserStore } from '@/store';
  import { useRouter } from 'vue-router';
  import { reactive, ref, onMounted } from 'vue';
  import dayjs from 'dayjs';
  import { PutEquipment } from '@/api/equipment-management/equipment-list';

  import {
    PostFaultEquipment,
    GetFaultEquipmentList,
    DelFaultEquipment,
    PutFaultEquipment,
  } from '@/api/equipment-management/equipment-maintain-manager';
  import equipmentRepair from '../../components/equipment-repair/index.vue';

  const router = useRouter();
  const title: string = '维修待派工列表';
  const breadCrumb: string[] = [
    '设备管理',
    '设备维护（管理）',
    '维修待派工列表',
  ];
  const userStore = useUserStore();
  // 表格配置
  const args = reactive({
    stripe: true,
    bordered: {
      headerCell: true,
    },
    rowSelection: {
      type: 'checkbox',
    },
  });

  let tableRef = ref(); // 储存table的ref

  // 储存某行的信息维修待派工列表
  const form = reactive({
    list: {},
  });

  let type = ref(1); // 判断弹出框的type

  let currNumber = ref(''); // 第一个搜索框
  let currSelectName = ref(''); // 储存第一个搜索框的下拉框值

  let currEquipName = ref(''); // 设备名称搜索框
  const personnelVisible = ref(false);
  // 获取表格数据
  const getData = async (pageData?: any) => {
    try {
      const data: any = {};
      if (currNumber.value.trim() !== '')
        data[currSelectName.value] = currNumber.value;
      if (currEquipName.value.trim() !== '')
        data.equipName = currEquipName.value;
      const res = await GetFaultEquipmentList({
        ...pageData,
        repairState: 1,
        authority: 1,
        ...data,
      });
      return Promise.resolve(res);
    } catch (error: unknown) {
      console.log(error);
    }
  };

  let repairVisible = ref(false); // 判断故障报修弹出框是否弹出

  // 点击故障报修按钮
  const repairFault = () => {
    type.value = 1;
    repairVisible.value = true;
  };

  // 搜索框事件
  const search = () => {
    tableRef.value.loadData();
  };

  // 弹出框的自定义事件
  const equipmentEmit = async (list: any, type: number) => {
    try {
      if (type === 1) {
        list.repairState = 1; // 待派工状态
        await PostFaultEquipment({
          equipNumber: list.equipNumber,
          equipName: list.equipName,
          workshop: list.workshop,
          reportTime: list.reportTime,
          reporterId:
            userStore.userId ||
            JSON.parse(sessionStorage.getItem('loginInfo') as string).id,
          description: list.description,
          equipmentRepairPicture: list.equipmentRepairPicture,
          equipmentId: list.equipmentId,
        });
        await PutEquipment({ id: list.equipmentId, useState: 3 });
        tableRef.value.loadData();
        repairVisible.value = false;
      } else if (type === 3) {
        await PostFaultEquipment({
          equipNumber: list.equipNumber,
          number: list.number,
          equipName: list.equipName,
          workshop: list.workshop,
          reportTime: list.reportTime,
          reporterId: list.reporterId,
          description: list.description,
          picture: list.picture,
          repairState: list.repairState,
          repairerId: list.repairerId,
          id: list.id,
          equipmentId: list.equipmentId,
          authority: list.authority,
        });
        tableRef.value.loadData();
      } else if (type === 4) {
        await PostFaultEquipment({
          repairState: list.repairState,
          repairerId: list.repairerId,
          id: list.id,
          authority: list.authority,
          repairBeginTime: Number(list.repairBeginTime),
          repairEndTime: Number(list.repairEndTime),
          isReplaceparts: list.isReplaceparts,
          isSubcontracting: list.isSubcontracting,
          faultAnalysis: list.faultAnalysis,
          treatmentMeasures: list.treatmentMeasures,
          equipmentId: list.equipmentId,
        });
        repairVisible.value = false;
        tableRef.value.loadData();
      }
      form.list = {
        equipNumber: '', // 设备编码
        equipName: '', // 设备名称
        workshop: '', // 所属车间
        reportTime: undefined, // 报修时间
        reporterId: undefined, // 报修人id
        repairerId: undefined, // 维修人id
        description: '', // 故障描述
        equipmentRepairPicture: [], // 图片上传
      };
    } catch (error: unknown) {
      console.log(error);
    }
  };

  // 表格故障描述中的的查看按钮
  const goDetail = (record: any, currType: number) => {
    type.value = currType;
    form.list = record;
    repairVisible.value = true;
  };

  // 删除一项
  const deleteItem = async (id: number) => {
    try {
      await DelFaultEquipment({
        id,
        authority: 1,
      });
      tableRef.value.loadData();
    } catch (error: unknown) {
      console.log(error);
    }
  };

  // 重置
  const reset = () => {
    currNumber.value = '';
    currSelectName.value = '';
    currEquipName.value = '';
    tableRef.value.loadData();
  };
  const changePersonnelId = async (e: { id: number; name: string }) => {
    //
    try {
      for (const ele of tableRef.value.selectedKeys) {
        // eslint-disable-next-line no-await-in-loop
        await PutFaultEquipment({
          id: ele,
          repairerId: e.id,
          repairState: 2,
        });
      }
      for (const ele of tableRef.value.selectedList) {
        // eslint-disable-next-line no-await-in-loop
        await PutEquipment({
          id: ele.equipmentId,
          useState: 3,
        });
      }
      tableRef.value.selectedKeys = [];
      tableRef.value.loadData();
    } catch (error) {
      Message.error(`${error}`);
    }
  };
  const open = () => {
    try {
      if (
        !tableRef.value.selectedKeys ||
        tableRef.value.selectedKeys.length === 0
      )
        throw new Error('请选择维修的数据');
      tableRef.value.selectedList.forEach((ele: any) => {
        if (ele.repairState !== 1) {
          throw new Error('请选择正确的数据');
        }
      });
      personnelVisible.value = true;
    } catch (error) {
      console.log(error);
      Message.error(`${error}`);
    }
  };
</script>

<style scoped lang="less">
  .content {
    padding: 10px 40px;

    &-header {
      display: flex;
      width: 100%;
      height: 40px;
      margin-bottom: 10px;
      margin-top: 5px;
      :deep(.arco-btn-secondary) {
        color: #165dff;
      }
    }

    .repair-state {
      display: flex;
      justify-content: center;
      text-align: center;
      .cycle {
        position: relative;
        width: 16px;
        height: 16px;
        border-radius: 50%;
        content: '';
        display: inline-block;
        top: 3px;
        right: 10px;
      }
    }

    // 待派工
    .waitJob {
      color: #ccc;
    }
    .waitJob-cycle {
      background-color: #ccc;
    }

    // 维修中
    .waitRepair {
      color: #ccc;
    }
    .waitRepair-cycle {
      background-color: #ccc;
    }
    // 进行中
    .running {
      color: #3d7eff;
    }
    .running-cycle {
      background-color: #3d7eff;
    }
    // 需委外
    .needOut {
      color: #f90;
    }
    .needOut-cycle {
      background-color: #f90;
    }
    // 已委外
    .outing {
      color: #3cf;
    }
    .outing-cycle {
      background-color: #3cf;
    }
    // 已完工
    .finish {
      color: #31c27c;
    }
    .finish-cycle {
      background-color: #31c27c;
    }
  }
</style>
